<?php 
/**********************************************************
  eCode Marketing System
  Version 0.1
  Login Handler (/admin/handler.login.php)
**********************************************************/

// Require configuration
define("FROMSCRIPT", true);
require dirname(__FILE__) . "/../config.php";

// Start session if not already started
session_start();

if(isset($_SESSION['login_t'])) {

	/* If we're logged in, take us to the admin menu page and
	ensure the rest of the code isn't run */

	header("Location: /admin/index.php");
	exit;
}

// Try to get user info from user table
$userinfo = $db->get_row("SELECT * FROM `" . DB_TBL_PREFIX . "users` WHERE `username` = '" .  $db->escape($_POST['username']) . "'");
	
	if(!isset($_POST['username']) || $_POST['username'] == '') {
		// Username not specified, set error and transfer back to login form
		$_SESSION['error'] = "<span class=\"error\">ERROR</span>: Username not specified. Please try again.";
		header("Location: /admin/login.php");
		exit;
	} else if($userinfo == false) {
		// User not found, set error and transfer back to login form
		$_SESSION['error'] = "<span class=\"error\">ERROR</span>: Username invalid. Please try again.";
		$_SESSION['username'] = $userinfo->username;
		header("Location: /admin/login.php");
		exit;
	} else if($userinfo->active != 1) {
		// Username inactive, set error and transfer back to login form
		$_SESSION['error'] = "<span class=\"error\">ERROR</span>: Your account has been disabled. Please contact your administrator.";
		$_SESSION['username'] = $userinfo->username;
		header("Location: /admin/login.php");
		exit;	
        } else if(md5($_POST['password']) != $userinfo->password) {
		// Password invalid, set error and transfer back to login form
		$_SESSION['error'] = "<span class=\"error\">ERROR</span>: Password invalid. Please try again.";
		$_SESSION['username'] = $userinfo->username;
		header("Location: /admin/login.php");
		exit;
	} else {
		// Valid login information, set session
		$_SESSION['username'] = $userinfo->username;
		$_SESSION['displayname'] = $userinfo->display_name;
		$_SESSION['is_admin'] = $userinfo->is_admin;
		$_SESSION['login_t'] = time();

		// Clear any errors
		if(isset($_SESSION['error'])) {
			$_SESSION['error'] = null;
			unset($_SESSION['error']);
		}

		// Transfer to the administration menu
		header("Location: /admin/index.php");
		exit;
	}
?>